/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package unilearn.util.web;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Yat
 */
public class Download {

    public static void doDownload(HttpServletResponse resp, String fileName, byte[] fileBytes) throws IOException, ServletException {
        ServletOutputStream sos = resp.getOutputStream();

        resp.setContentType("application/octet-stream");
        resp.setContentLength(fileBytes.length);
        resp.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

        DataInputStream dis = new DataInputStream(new ByteArrayInputStream(fileBytes));

        sos.write(fileBytes);

        dis.close();
        sos.flush();
        sos.close();
    }
//    public void doDownload(HttpServletRequest request, HttpServletResponse response, ServletContext context, String fileName, byte[] fileBytes) throws Exception {
//        ServletOutputStream sos = null;
//        DataInputStream dis = null;
//        ByteArrayInputStream bais = null;
//
//        try {
//            int length = 0;
//            sos = response.getOutputStream();
//            //ServletContext context = getServletConfig().getServletContext();
//            String mimetype = context.getMimeType(fileName);
//
//            response.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
//            response.setContentLength(fileBytes.length);
//            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
//
//            byte[] buf = new byte[1024];
//            bais = new ByteArrayInputStream(fileBytes);
//            dis = new DataInputStream(bais);
//
//            while ((dis != null) && ((length = dis.read(buf)) != -1)) {
//                sos.write(buf, 0, length);
//            }
//
//        } catch (Exception e) {
//            System.out.println(Download.class.getName() + "[doDownload]\nException: " + e.toString());
//            throw e;
//        } finally {
////            try {
////                if (dis != null) {
////                    dis.close();
////                }
////
////                if (sos != null) {
////                    sos.flush();
////                    sos.close();
////                }
////
////                if (bais != null) {
////                    bais.close();
////                }
////            } catch (Exception e) {
////                System.out.println(Download.class.getName() + "[doDownload/finally]\nException: " + e.toString());
////                throw e;
////            }
//        }
//    }
}
